<template>
  <div class="SearchSuggestion">
    <van-cell
      @click="onSearch(item)"
      v-for="item in suggestions"
      :key="item"
      icon="search"
    >
      <template #title>
        <div v-html="hightText(item)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  beforeDestroy () {
    clearTimeout(this.setId)
  },
  watch: {
    searchText: {
      immediate: true,
      async handler (newVal) {
        if (this.setId) {
          clearTimeout(this.setId)
        }
        this.setId = setTimeout(async () => {
          const res = await getSearchSuggestion(newVal)
          this.suggestions = res.options
        }, 700)
      }
    }
  },
  data () {
    return {
      suggestions: []
    }
  },

  created () {},

  methods: {
    hightText (item) {
      const replaceStr =
        '<span style="color: red">' + this.searchText + '</span>'
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, replaceStr)
    },
    onSearch (item) {
      console.log(item)
      this.$emit('onSearch', item)
    }
  }
}
</script>

<style scoped lang="less"></style>
